﻿using System;
using System.Collections.Generic;
using FullCoreControllers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
 
using System.Linq;
using System.Threading.Tasks;
using SystemAPi.JWT;
using System.IO;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Hosting;
using FullCoreDBModels;

namespace PhotoSpace.Controllers
{
    public class UpLoadController : APIControllerRoot
    {

        private readonly IHostingEnvironment _hostingEnvironment;
        public UpLoadController(IHostingEnvironment host)
        {
            _hostingEnvironment = host;
        }
        /// <summary>
        /// 本地上传图片信息至服务器处理
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public CommonResult SaveImg()
        {
            CommonResult res = new CommonResult() {ErrMsg="",Result=false,ReturnData="" };
            foreach (FormFile file in Request.Form.Files)
            {
                #region 文件校验
                string exten = Path.GetExtension(file.FileName).ToLower();
                //扩展名不符合要求就不处理
                if (exten != ".jpg" && exten != ".png") continue;
                long size = file.Length / 1024; //文件大小KB
                if (size > 1024)
                {
                    res.ErrMsg = "存在过大文件！";
                    continue;
                } 
                #endregion
                string fileName = Guid.NewGuid().ToString();           
                string filePath = "/uploads/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/";//存储路径    一般情况下都是uploads文件夹           
                string fullpath = Path.Combine(_hostingEnvironment.ContentRootPath, filePath); //校验文件夹是否存在  不存在进行创建
                if (!Directory.Exists(fullpath))
                {
                    Directory.CreateDirectory(fullpath);
                }
                string fullName = fullpath + fileName + exten;
                using (FileStream stream = new FileStream(fullName, FileMode.Create, FileAccess.Write))
                {
                    file.CopyTo(stream);
                    stream.Flush();
                }
               
            }
            res.Result = true;
            res.ReturnData = "上传成功";
            return res;
        }
    }
}
